package com.flyshop.module.security.service;

import com.flyshop.core.entity.DataVo;
import com.flyshop.core.entity.PageVo;
import com.flyshop.module.security.dao.PermissionDao;
import com.flyshop.module.security.dao.RoleDao;
import com.flyshop.module.security.model.Permission;
import com.flyshop.module.security.model.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.transaction.Transactional;
import java.util.*;

@Service
public class PermissionService {
    @Autowired
    private PermissionDao dao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    WebApplicationContext applicationContext;

    //同步并更新所有权限
    public boolean getSyncAllPermission(){
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo,HandlerMethod> map = mapping.getHandlerMethods();
        List<String> urlList = new ArrayList<>();
        for (RequestMappingInfo info : map.keySet()){
            //获取url的Set集合，一个方法可能对应多个url
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            for (String url : patterns){
                Permission per=new Permission();
                String urlstr=info.getPatternsCondition().toString();
                //替换花括号和里面所有内容为*
                urlstr=urlstr.replaceAll("\\{([^\\}]+)\\}", "*");
                //替换前后中括号
                urlstr=urlstr.replaceAll("[\\[\\]]", "");
                // 只处理后台管理 action，其它跳过
                if (urlstr.startsWith("/admin")) {
                    per.setActionKey(urlstr);
                    per.setController(map.get(info).getBean().toString());
                    if (!checkPermission(per.getActionKey(), per.getController())) {
                        int permissionId=dao.addPermission(per);
                        if(!this.markAssignedPermissions(1,per.getId())){
                            //默认超级管理员组添加新的权限关联
                            roleDao.addRolePermission(1,per.getId());
                        }
                    }
                }
            }
        }
        return true;
    }
    // ///////////////////////////////
    // /////        删除      ////////
    // ///////////////////////////////
    //按id删除权限权限
    @Transactional
    public boolean deletePermission(int id){
        int totalCount = dao.deletePermission(id);
        dao.deleteRolePermission(id);
        return totalCount > 0 ? true : false;
    }

    // ///////////////////////////////
    // /////        修改      ////////
    // ///////////////////////////////
    //添加产品分类信息
    public DataVo updatePermissions(Permission permission){
        DataVo data = DataVo.failure("操作失败");
        if(dao.updatePermissions(permission)>0){
            data=DataVo.success("修改成功");
        }else{
            data=DataVo.failure("修改失败！");
        }
        return data;
    }

    // ///////////////////////////////
    // /////       查询       ////////
    // ///////////////////////////////
    //按id查询权限组信息
    public Permission findPermissionById(int id){
        return dao.findPermissionById(id);
    }

    //检查该权限是否存在
    public boolean checkPermission(String actionKey, String controller) {
        int totalCount = dao.checkPermission(actionKey,controller);
        return totalCount > 0 ? true : false;
    }

    /**
     * 查询该用户所有权限url
     *
     * @param userId
     * @return
     */
    public List<Permission> findPermissionByUserId(int userId) {
        return dao.findPermissionByUserId(userId);
    }

    /**
     * 权限翻页查询
     *
     * @param pageNum
     * @param rows
     * @return
     * @throws Exception
     */
    public PageVo<Permission> getPermissionListPage(int pageNum, int rows) {
        PageVo<Permission> pageVo = new PageVo<Permission>(pageNum);
        pageVo.setRows(rows);
        List<Permission> list = new ArrayList<Permission>();
        pageVo.setList(dao.getPermissionList(pageVo.getOffset(), pageVo.getRows()));
        pageVo.setCount(dao.getPermissionCount());
        return pageVo;
    }

    //查询所有权限list
    public List<Permission> getAllPermissions() {
        return dao.getAllPermissions();
    }

    /**
     * 标记出 role 拥有的权限，用于在界面输出 checkbox 的 checked 属性
     * 未来用 permission left join role_permission 来优化
     */
    public boolean markAssignedPermissions(int roleId,int permissionId) {
        int totalCount = dao.markAssignedPermissions(roleId,permissionId);
        return totalCount > 0 ? true : false;
    }

    /**
     * 根据 controller 将 permission 进行分组
     */
    public LinkedHashMap<String, List<Permission>> groupByController(List<Permission> permissionList) {
        LinkedHashMap<String, List<Permission>> ret = new LinkedHashMap<String, List<Permission>>();

        for (Permission permission : permissionList) {
            String controller = permission.getController();
            List<Permission> list = ret.get(controller);
            if (list == null) {
                list = new ArrayList<Permission>();
                ret.put(controller, list);
            }

            list.add(permission);
        }

        return ret;
    }
}
